#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Compare different mesh visualization approaches:
1. Raw mesh (like Gmsh shows it)
2. Surface extraction (what the original script does)
3. Processed view (with filtering and coloring)
"""

import pyvista as pv
import numpy as np
import os
import sys

# Add the dragonfly_simulation directory to Python path
DRAGONFLY_SIM_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(DRAGONFLY_SIM_ROOT)

import config

def compare_all_views():
    """Show raw mesh, surface extraction, and processed view side by side."""
    
    mesh_file = os.path.join(DRAGONFLY_SIM_ROOT, config.MESH_FILE)
    
    if not os.path.exists(mesh_file):
        print(f"ERROR: Mesh file not found at {mesh_file}")
        return
    
    print("Loading mesh for comparison...")
    mesh = pv.read(mesh_file)
    print(f"Mesh loaded: {mesh.n_points} points, {mesh.n_cells} cells")
    
    # Create three-panel comparison (off_screen=True for saving images)
    plotter = pv.Plotter(shape=(1, 3), window_size=[2400, 800], off_screen=True)
    
    # Panel 1: Raw mesh (like Gmsh)
    plotter.subplot(0, 0)
    plotter.add_text("Raw Mesh\n(Like Gmsh)", position='upper_left', font_size=14)
    plotter.add_mesh(mesh, show_edges=True, opacity=0.8, color='lightgray')
    plotter.add_axes()
    
    # Panel 2: Surface extraction only
    plotter.subplot(0, 1)
    plotter.add_text("Surface Extraction\n(Boundaries Only)", position='upper_left', font_size=14)
    surface = mesh.extract_surface()
    plotter.add_mesh(surface, show_edges=True, opacity=0.8, color='lightblue')
    plotter.add_axes()
    
    # Panel 3: Processed view (with filtering and coloring)
    plotter.subplot(0, 2)
    plotter.add_text("Processed View\n(Original Script)", position='upper_left', font_size=14)
    
    # Apply the same processing as the original script
    surface = mesh.extract_surface()
    center = surface.cell_centers()
    distances = np.linalg.norm(center.points, axis=1)
    wing_threshold = 0.05  # 5cm from origin
    
    wing_cells = np.where(distances < wing_threshold)[0]
    
    if len(wing_cells) > 0:
        # Wing surface in red
        selection = np.zeros(surface.n_cells, dtype=bool)
        selection[wing_cells] = True
        wing_surface = surface.extract_cells(selection)
        plotter.add_mesh(wing_surface, color='red', opacity=1.0)
        
        # Domain boundaries in transparent blue
        domain_cells = np.where(distances >= wing_threshold)[0]
        selection = np.zeros(surface.n_cells, dtype=bool)
        selection[domain_cells] = True
        domain_surface = surface.extract_cells(selection)
        plotter.add_mesh(domain_surface, color='lightblue', opacity=0.3)
    else:
        plotter.add_mesh(surface, color='lightblue', opacity=0.3)
    
    # Add Y=0 slice
    slice_y = mesh.slice(normal='y', origin=(0, 0, 0))
    plotter.add_mesh(slice_y, show_edges=True, opacity=0.8, color='gray')
    
    plotter.add_axes()
    
    # Save the comparison as PNG
    output_path = "mesh_comparison_visualization.png"
    plotter.screenshot(output_path)
    print(f"\nThree-way comparison saved to: {output_path}")
    print("Left: Raw mesh (similar to Gmsh)")
    print("Middle: Surface extraction only")
    print("Right: Processed view (original script)")
    plotter.close()

def explain_differences():
    """Print explanation of the differences."""
    
    print("\n" + "="*60)
    print("EXPLANATION OF DIFFERENCES")
    print("="*60)
    
    print("\n1. RAW MESH (Left panel - like Gmsh):")
    print("   - Shows ALL mesh elements (tetrahedral cells)")
    print("   - Displays internal structure")
    print("   - No filtering or processing")
    print("   - Gray wireframe showing actual mesh")
    
    print("\n2. SURFACE EXTRACTION (Middle panel):")
    print("   - Shows only BOUNDARY faces")
    print("   - Internal mesh structure hidden")
    print("   - Single color (blue)")
    print("   - This is what PyVista.extract_surface() does")
    
    print("\n3. PROCESSED VIEW (Right panel - original script):")
    print("   - Surface extraction + distance filtering")
    print("   - Red: 'Wing' cells (within 5cm of origin)")
    print("   - Blue: 'Domain' cells (farther from origin)")
    print("   - Gray: Y=0 slice showing internal structure")
    print("   - Multiple colors and transparency")
    
    print("\n" + "="*60)
    print("WHY THEY LOOK DIFFERENT:")
    print("="*60)
    
    print("\n• Gmsh shows the COMPLETE mesh as generated")
    print("• PyVista applies FILTERS and PROCESSING")
    print("• Different rendering engines and lighting")
    print("• Different default camera angles")
    print("• Original script adds interpretive visualization")

if __name__ == "__main__":
    print("=== Mesh Visualization Comparison ===")
    compare_all_views()
    explain_differences() 